package metu.tespit.session.course;

import java.io.File;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import metu.tespit.entitiy.accountManagement.User;
import metu.tespit.entitiy.accountManagement.UserRole;
import metu.tespit.entity.course.Course;
import metu.tespit.entity.course.Schedule;
import metu.tespit.session.EntityManager.ExtendedEntityHome;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.util.Base64;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;


/**
 
 * @created 22 Nis 2012
 */
@Name("courseHome")
@Scope(ScopeType.CONVERSATION)
public class CourseHome extends ExtendedEntityHome<Course>{
	
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7768656870164264708L;

	private final String saltstr="C47t1TuP6=4159W";

	@In
	private EntityManager entityManager;
	
	private List<User> studentsToBeAdded=new ArrayList<User>();
	
	public Long getCourseId() {
		return (Long) getId();
	}

	public void setCourseId(Long courseId) {
		setId(courseId);
		
	}

	public String persist(){

		Schedule s=new Schedule();
		s.setCourse(instance);
		instance.setSchedule(s);
		clearUTBSList();
		return super.persist();

	}
	
	@SuppressWarnings("unchecked")
	public void listener(UploadEvent event) throws Exception{

		UserRole studentRole= (UserRole)entityManager.createQuery("Select ur from UserRole ur where ur.roleName='Student'").getSingleResult();
		
		List<String> userList =(List<String>)entityManager.createQuery("Select u.username from User u where :course member of u.coursesTaken").setParameter("course", this.instance).getResultList();
		
		DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
		UploadItem item = event.getUploadItem();
		File file =item.getFile();
		RandomAccessFile f = new RandomAccessFile(file, "r");
		byte[] b = new byte[(int)f.length()];
		f.read(b);


		String str = new String(b);
		String[] studs= str.split("\r\n");

		for (String stud : studs){
			String[] studentDetais=stud.split(" ");

			User us=new User();
			
			us.setUsername(studentDetais[0]);
			
			if (userList.contains(us.getUsername()))
				break;
			
			us.setPassword(getHash(studentDetais[studentDetais.length-3],saltstr));
			us.setEmail(studentDetais[studentDetais.length-2]);
			us.setDueDate(df.parse(studentDetais[studentDetais.length-1]));
			int arguments=studentDetais.length-4;
			
			if(arguments>3){
				
				us.setSurname(studentDetais[1]+" "+studentDetais[2]);
				us.setName("");
				for(int i=0; i<arguments-2; i++){
					
					us.setName(us.getName()+studentDetais[i+3]+" ");
					
				}
				
				
			}
			else if(arguments==3){
				us.setSurname(studentDetais[1]);
				us.setName(studentDetais[2]+" "+studentDetais[3]);
			}
			else{
				us.setSurname(studentDetais[1]);
				us.setName(studentDetais[2]);
			}
			us.setName(us.getName().trim());

			us.getCoursesTaken().add(instance);
			us.getUserRoles().add(studentRole);
			
			
			
			this.getStudentsToBeAdded().add(us);
		}
	}  


	public String updateForBacthStudentList(){
		for(User u:getStudentsToBeAdded()){
			entityManager.persist(u);
			u.getCoursesTaken().add(this.instance);
			this.instance.getStudents().add(u);
			
		}
		return super.update();
		
	}
	
	
	@SuppressWarnings("unchecked")
	public String updateForStudentList(){
		List<User> userList =(List<User>)entityManager.createQuery("Select u from User u where :course member of u.coursesTaken").setParameter("course", this.instance).getResultList();

		for (User us : this.instance.getStudents()){
			userList.remove(us);
			us.getCoursesTaken().add(instance);
		}
		for (User us : userList){
			us.getCoursesTaken().remove(this.instance);
		}
		return super.update();
	}

	private String getHash(String password,String saltPhrase)throws Exception{
		MessageDigest md = MessageDigest.getInstance("MD5");

		md.update(saltPhrase.getBytes());

		byte[] salt = md.digest();

		md.reset();

		md.update(password.getBytes("UTF-8"));

		md.update(salt);

		byte[] raw = md.digest();

		return new String(Base64.encodeBytes(raw));
	}

	public void clearInstance(){
		super.clearInstance();
		clearUTBSList();
	}
	
	public void clearUTBSList(){
		
		this.studentsToBeAdded = new ArrayList<User>();
		
		
	}
	
	public void setStudentsToBeAdded(List<User> studentsToBeAdded) {
		this.studentsToBeAdded = studentsToBeAdded;
	}

	public List<User> getStudentsToBeAdded() {

		return studentsToBeAdded;
	}

}
